package com.yuchen.advsdk.manager;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuchen.advsdk.Constant;
import com.yuchen.advsdk.eb.EbPreDownload;
import com.yuchen.advsdk.net.AJsonParser;
import com.yuchen.advsdk.net.API;
import com.yuchen.advsdk.net.NetWork;
import com.yuchen.advsdk.net.NetWorkStringCallBack;
import com.yuchen.advsdk.util.AppUtil;
import com.yuchen.advsdk.util.AssetsFileUtil;
import com.yuchen.advsdk.util.AsyncTaskUtil;
import com.yuchen.advsdk.util.AuthImpl;
import com.yuchen.advsdk.util.DateTimeUtil;
import com.yuchen.advsdk.util.DeviceUtil;
import com.yuchen.advsdk.util.FileUtil;
import com.yuchen.advsdk.util.LogUtils;
import com.yuchen.advsdk.util.NetUtil;
import com.yuchen.advsdk.util.SPManager;
import com.yuchen.advsdk.util.SafeHandler;
import com.yuchen.advsdk.util.SafeHandlerMsgCallback;
import com.yuchen.advsdk.weight.AdvPercentView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class LayoutPollManager implements SafeHandlerMsgCallback {

    private static final String TAG = "LayoutPollManager";
    private static final int MSG_POLL = 1;

    private Context context;
    private static LayoutPollManager instance;
    private static SafeHandler handler;
    private Config config;
    private boolean isAuth;
    private AdvPercentView advPercentView;
    private boolean isRunning;
    private boolean isPause;

    private LayoutPollManager() {
        EventBus.getDefault().register(this);
        handler = new SafeHandler();
        handler.regist(this);
        config = new Config();
//        config.setHost(API.newInstance().hostHttp);
        config.setDuration(5 * 1000);
    }

    public static synchronized LayoutPollManager getInstance() {
        if (instance == null) {
            instance = new LayoutPollManager();
        }
        return instance;
    }

    public void unbindAdvPercentView(){
        if (advPercentView!=null){
            this.advPercentView.setOnInitListener(null);
            this.advPercentView.setOnParseLayoutListener(null);
            advPercentView.onDestory();
            this.advPercentView = null;
        }

    }
    public void bindAdvPercentView(final AdvPercentView advPercentView) {
        this.advPercentView = advPercentView;
        this.advPercentView.setOnInitListener(new AdvPercentView.OnInitListener() {
            @Override
            public void start() {

            }

            @Override
            public void success() {
                layoutPoll();
            }
        });
        this.advPercentView.setOnParseLayoutListener(new AdvPercentView.OnParseLayoutListener() {
            @Override
            public void start() {

            }

            @Override
            public void success() {
                advPercentView.start();
            }

            @Override
            public void error(String msg) {
                Log.d(TAG,"setOnParseLayoutListener.error : " + msg);
            }
        });
    }

    public final void init(Activity context) {
        isPause = false;
        this.context = context;
        SPManager.ini(context);
//        API.hostHttp = config.getHost();
        config.setViewModel(AdvPercentView.Model.ON_LINE);
        config.setOffLineLayoutName("land_1080p_1");
        LitePal.initialize(context);

    }

    public interface AuthCallBack {
        void start();

        void success();

        void error(String msg);
    }

    private AuthCallBack authCallBack;

    public AuthCallBack getAuthCallBack() {
        return authCallBack;
    }

    public void setAuthCallBack(AuthCallBack authCallBack) {
        this.authCallBack = authCallBack;
    }

    public final void reAuth() {
        SPManager.remove(Constant.appId);
        SPManager.remove(Constant.appSecret);
        SPManager.remove(Constant.licenseCode);
        auth();
    }

    public final void auth() {
        if (authCallBack != null) {
            authCallBack.start();
        }
        if (config.getViewModel() == AdvPercentView.Model.OFF_LINE || config.getViewModel() == AdvPercentView.Model.OFF_LINE_ZIP) {
            authJni(false);
        } else {
//            String appId = SPManager.getString(Constant.appId);
//            String appSecret = SPManager.getString(Constant.appSecret);
//            String licenseCode = SPManager.getString(Constant.licenseCode);
//            if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(appSecret)) {
//                showLicenseCodeDialog();
//            } else {
            regist(null, null, null,null);
//            }

        }
    }

//    private LicenseCodeDialog licenseCodeDialog;

    private void showLicenseCodeDialog() {
//        if (licenseCodeDialog == null) {
//            licenseCodeDialog = new LicenseCodeDialog(context);
//            licenseCodeDialog.setOnCommitListener(new LicenseCodeDialog.OnCommitListener() {
//                @Override
//                public void commit(String appId, String appSecret, String licenseCode) {
////                    SPManager.put(Constant.appSecret, appSecret);
////                    SPManager.put(Constant.appId, appId);
////                    SPManager.put(Constant.licenseCode, licenseCode);
//                    hideLicenseCodeDialog();
//                    regist(appId, appSecret, licenseCode);
//                }
//            });
//        }
//        licenseCodeDialog.show();
    }

    private void hideLicenseCodeDialog() {
//        if (licenseCodeDialog != null && licenseCodeDialog.isShowing()) {
//            licenseCodeDialog.dismiss();
//        }
    }

    public interface RegistCallBack{
        void success(long deviceId,String deviceCode);
        void error(String errorMsg);
    }

    private RegistCallBack registCallBack;

    public void setRegistCallBack(RegistCallBack registCallBack) {
        this.registCallBack = registCallBack;
    }

    public void regist(final String appId, final String appSecret, final String authorizationCode) {
        regist(appId,appSecret,authorizationCode,null);
    }

    public void regist(final String appId, final String appSecret, final String authorizationCode,String deviceName) {
        final JSONObject param = new JSONObject();
        param.put(Constant.deviceSn, DeviceUtil.getDeviceSn());//getEthernetMacAddress()
        param.put("appVersionName", AppUtil.getVersionName(context));
        param.put("appVersionCode", AppUtil.getVersionCode(context));
        param.put("deviceName",deviceName);
//        param.put(Constaint.appId, AppUtil.getAppMetaDataString(context, Constaint.appIdMeta));
//        param.put(Constaint.appSecret, AppUtil.getAppMetaDataString(context, Constaint.appSecretMeta));
        param.put(Constant.appId, appId);
        param.put(Constant.appSecret, appSecret);
        param.put("authorizationCode", authorizationCode);
        NetWork.getInstance().postString()
                .url(API.newInstance().regist)
                .isLog(false)
                .postStringContent(param.toJSONString())
                .build()
                .execute(new NetWorkStringCallBack() {
                    @Override
                    public void onError(String msg) {
//                        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
//                        showLicenseCodeDialog();
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                regist(appId, appSecret, authorizationCode);
//                            }
//                        }, 5000);
//                        if (authCallBack != null) {
//                            authCallBack.error(msg);
//                        }
                        if (registCallBack!=null){
                            registCallBack.error(msg);
                        }
                    }

                    @Override
                    public void onResponse(String json) {
                        AJsonParser parser = AJsonParser.parser(json);
                        if (parser.isOk() && parser.parseContent()!=null) {
                            long deviceId = parser.parseContent().getLongValue("id");
                            String deviceCode = parser.parseContent().getString("deviceCode");
                            SPManager.put(Constant.deviceId, deviceId);
                            SPManager.put(Constant.deviceCode,deviceCode);
//                            advPercentView.init(AdvPercentView.Model.OFF_LINE);
                            if (authCallBack != null) {
//                                authCallBack.success();
                                authJni(true);
                            }
                            if (registCallBack!=null){
                                registCallBack.success(deviceId,deviceCode);
                            }
                        } else if (parser.parseCode() == 10002){
                            showLicenseCodeDialog();
//                            Toast.makeText(context, parser.parseMessage(), Toast.LENGTH_SHORT).show();
//                            ToastUtils.show("设备未授权，请进行授权操作");
//                            authCallBack.error(parser.parseMessage());
                        }else {
                            showLicenseCodeDialog();
//                            Toast.makeText(context, parser.parseMessage(), Toast.LENGTH_SHORT).show();
//                            ToastUtils.show(parser.parseMessage());
                            Log.d(TAG,parser.parseMessage());
                            if (registCallBack!=null){
                                registCallBack.error(parser.parseMessage());
                            }
                        }
                    }
                });
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEbPreDownload(EbPreDownload eb) {
//        preDownload();
//    }

    public String getDeviceCode(){
        return SPManager.getString(Constant.deviceCode);
    }

    private void authJni(boolean overWrite) {
        final File licenseFile = new File("/storage/emulated/0/license.txt");
        if (overWrite) {
            if (licenseFile.exists()) {
                licenseFile.delete();
            }
        }
//        final Auth auth = new Auth();
        final AuthImpl auth = new AuthImpl();
        if (licenseFile.exists()) {
//            0 授权通过
//            1 没有授权文件
//            2 授权验证失败
//            3 读取不到种子
            int code = auth.auth();
            if (code == 0) {
                isAuth = true;
                authCallBack.success();
            } else if (code == 1) {
                authCallBack.error("未找到授权文件");
            } else if (code == 2) {
                authCallBack.error("授权验证失败");
            } else if (code == 3) {
                authCallBack.error("无法获取设备信息");
            }
        } else {
            if (config.getViewModel() == AdvPercentView.Model.OFF_LINE || config.getViewModel() == AdvPercentView.Model.OFF_LINE_ZIP) {
                Toast.makeText(context, "授权文件不存，请切换至在线模式进行授权或者加载授权文件", Toast.LENGTH_SHORT).show();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        SPManager.put(Constant.model, 1);
                        Toast.makeText(context, "设备即将自动重启", Toast.LENGTH_SHORT).show();
//                        ReStartException.reStart();
                    }
                }, 1000);
            } else {
                NetWork.getInstance()
                        .get()
                        .url(API.newInstance().authPath)
                        .addParam(Constant.deviceId, SPManager.getLong(Constant.deviceId))
//                    .addParam(Constaint.licenseCode,config.getLicenseCode())
                        .addParam(Constant.seed, auth.seed())
                        .build()
                        .execute(new NetWorkStringCallBack() {
                            @Override
                            public void onError(String msg) {
                                if (authCallBack != null) {
                                    authCallBack.error(msg);
                                }
                            }

                            @Override
                            public void onResponse(String json) {
                                AJsonParser parser = AJsonParser.parser(json);
                                if (parser.isOk()) {
                                    String lincnseTxt = parser.parseLincnseTxt();
                                    if (!licenseFile.exists()) {
                                        licenseFile.getParentFile().mkdirs();
                                    }
                                    try {
                                        FileWriter fw = new FileWriter(licenseFile);
                                        fw.write(lincnseTxt);
                                        fw.flush();
                                        fw.close();
                                        int code = auth.auth();
                                        if (code == 0) {
                                            isAuth = true;
                                            authCallBack.success();
                                        } else if (code == 1) {
                                            authCallBack.error("未找到授权文件");
                                        } else if (code == 2) {
                                            authCallBack.error("授权验证失败");
                                        } else if (code == 3) {
                                            authCallBack.error("无法获取设备信息");
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                        authCallBack.error(e.getMessage());
                                    }

                                }
                            }
                        });
            }
        }
    }


    public Config getConfig() {
        return config;
    }

    public void setConfig(Config config) {
        this.config = config;
    }

    public void onPause() {
        isPause = true;
        if (isRunning) {
//            stopRun();
            handler.sendEmptyMessage(MSG_POLL);
            isRunning = true;
            advPercentView.onPause();
        }
    }

    public void onResume() throws Exception {
        isPause = false;
        if (isRunning) {
            isRunning = false;
            startRun();
            advPercentView.onResume();
        }

    }

    public void onDestory() {
        if (advPercentView != null) {
            advPercentView.onDestory();
            advPercentView = null;
        }

        if (handler != null) {
            handler.unregist();
            handler = null;
        }
        EventBus.getDefault().unregister(this);
        instance = null;
    }

    public void startRun() throws Exception {
        if (!isAuth) {
            throw new Exception("LayoutPollManager is not auth success");
        }
        if (isRunning) {
            return;
        }
        isRunning = true;
        isPause = false;
        if (handler == null) {
            handler = new SafeHandler();
            handler.regist(this);
        }

        if (!TextUtils.isEmpty(advPercentView.getLayoutMd5())) {
            advPercentView.start();
        }
        handler.removeMessages(MSG_POLL);
        handler.sendEmptyMessage(MSG_POLL);
    }

    public void stopRun() {
        if (advPercentView.isPlaying) {
            advPercentView.stop();
        }
        isRunning = false;
        handler.removeMessages(MSG_POLL);
        isPause = false;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_POLL:
                layoutPoll();
                break;
        }
    }

    public boolean isAuth(){
        return isAuth;
    }

    public void layoutPoll() {
//        KLog.d("layoutPoll");
        if (!isAuth) {
            Log.d(TAG,"LayoutPollManager is not auth " + isAuth);
            return;
        }
        if (isPause && !isRunning) {
            handler.removeMessages(MSG_POLL);
            return;
        }
        handler.removeMessages(MSG_POLL);
//        if (config.getViewModel() != AdvPercentView.Model.ON_LINE) {
        handler.sendEmptyMessageDelayed(MSG_POLL, config.getDuration());
//        }
        if (AdvPercentView.Model.ON_LINE.equals(config.getViewModel())) {
            long aLong = SPManager.getLong(Constant.preDownloadTime);
            if (aLong != 0 && System.currentTimeMillis() - aLong > 7 * 24 * 3600 * 1000 && VideoDownloadManager.getInstance().isInited()) {
                preDownload();
            }
            NetWork.getInstance().get()
//                    .url(API.getDeviceLayoutInfo)
                    .url(API.newInstance().getNewDeviceLayoutInfo)
                    .addParam(Constant.netType, NetUtil.getCurrentNetType(context))
                    .addParam(Constant.deviceId, SPManager.getLong(Constant.deviceId))
                    .addParam(Constant.layoutMd5, TextUtils.isEmpty(advPercentView.getLayoutMd5()) ? "" : advPercentView.getLayoutMd5())
                    .build()
                    .execute(new NetWorkStringCallBack() {
                        @Override
                        public void onError(String msg) {

                        }

                        @Override
                        public void onResponse(String json) {
                            AJsonParser parser = AJsonParser.parser(json);
                            if (parser.isOk()) {
                                JSONObject content = parser.parseContent();
                                if (content == null) {
                                    return;
                                }else if ("{}".equals(content.toJSONString())){
                                    advPercentView.removeAllViews();
                                    advPercentView.addSettingView();
                                    advPercentView.setLayoutMd5("none");
                                    return;
                                }
                                String jsonLayout = content.getString("layoutText");
                                if (TextUtils.isEmpty(jsonLayout)) {
                                    return;
                                }
                                if (!advPercentView.isInit) {
                                    advPercentView.init(config.getViewModel());
                                } else {
                                    if (isPause && !isRunning) {
                                        return;
                                    }
                                    String stringMD5 = FileUtil.getStringMD5(jsonLayout);
                                    Log.d(TAG,"MD5: " + stringMD5 + " " + advPercentView.getLayoutMd5());
                                    Log.d(TAG,isRunning + " " + isPause);
                                    if (!TextUtils.isEmpty(stringMD5) && !stringMD5.equals(advPercentView.getLayoutMd5())) {
                                        advPercentView.parseLayout(jsonLayout, AdvPercentView.Model.ON_LINE);
                                        preDownload();
                                    }
                                }
                            }
                        }
                    });
        } else if (AdvPercentView.Model.OFF_LINE_ZIP.equals(config.getViewModel())) {
            final File zipFile = new File(Constant.path_base + "/layout.zip");
            if (zipFile.exists()) {
                AsyncTaskUtil.run(new AsyncTaskUtil.Task<String>() {
                    @Override
                    public void before() {

                    }

                    @Override
                    public String taskRun() {
                        return FileUtil.getFileMD5(zipFile);
                    }

                    @Override
                    public void success(String s) {
                        if (!advPercentView.isInit) {
                            advPercentView.init(config.getViewModel());
                        } else {
                            if (isPause && !isRunning) {
                                return;
                            }
                            Log.d(TAG,isRunning + " " + isPause);
                            Log.d(TAG,"MD5: " + s + " " + advPercentView.getLayoutMd5());
                            if (!TextUtils.isEmpty(s) && !s.equals(advPercentView.getLayoutMd5())) {
                                advPercentView.parseLayoutZip(zipFile);
                            }
                        }

                    }
                });
            } else {
                if (!advPercentView.isInit) {
                    advPercentView.init(config.getViewModel());
                }
            }
        } else if (AdvPercentView.Model.OFF_LINE.equals(config.getViewModel())) {
//            final File dir = new File(Constant.path_off_line);
            final File dir = new File(getConfig().getLocalDir());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            AsyncTaskUtil.run(new AsyncTaskUtil.Task<String>() {
                @Override
                public void before() {

                }

                @Override
                public String taskRun() {
//                    String json = AssetsFileUtil.readAssetsFile(context, SPManager.getString(Constant.layoutName, "land_1080p_1"), 10 * 1024 * 1024);
                    String json = getConfig().getLocalLayout();
                    if (TextUtils.isEmpty(json)) {
                        json = AssetsFileUtil.readAssetsFile(context, "land_1080p_1", 10 * 1024 * 1024);
                        SPManager.put(Constant.layoutName, "land_1080p_1");
                    }
                    JSONObject layout = JSON.parseObject(json);
                    JSONObject video = layout.getJSONObject("video");
                    JSONArray images = layout.getJSONArray("images");
                    JSONObject image = (images == null || images.isEmpty()) ? null : images.getJSONObject(0);
                    JSONArray marquees = layout.getJSONArray("marquees");
                    JSONObject marquee = (marquees == null || marquees.isEmpty()) ? null : marquees.getJSONObject(0);
                    try {
                        for (File file : dir.listFiles()) {
                            if (file.isFile()) {
                                if (video != null && isVideo(file)) {
                                    //视频文件
                                    JSONObject obj = new JSONObject();
                                    obj.put("url", file.getAbsolutePath());
                                    video.getJSONArray("data").add(obj);
                                } else if (image != null && isImage(file)) {
                                    JSONObject obj = new JSONObject();
                                    obj.put("url", file.getAbsolutePath());
                                    image.getJSONArray("data").add(obj);
                                } else if (marquee != null && "word.txt".endsWith(file.getName())) {
                                    JSONObject position = marquee.getJSONObject("position");
                                    JSONObject params = marquee.getJSONObject("params");
                                    List<String> lines = FileUtil.readLine(file.getAbsolutePath());
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("text", "未设置跑马灯内容");
                                    map.put("textSize", -1);
                                    map.put("textColor", "#FF0000");
                                    map.put("duration", -1);
                                    map.put("backgroundColor", "#FFFFFF");
//                                KLog.d("跑马灯内容:"+lines);
                                    for (String s : lines) {
                                        if (!TextUtils.isEmpty(s)) {
                                            String[] split = s.split(":");
                                            if (split != null && split.length == 2) {
                                                map.put(split[0], split[1]);
                                            }
                                        }
                                    }
                                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                                        if ("text".equals(entry.getKey())) {
                                            if (!TextUtils.isEmpty(entry.getValue().toString())) {
                                                marquee.put("data", entry.getValue());
                                            }
                                        } else if ("textSize".equals(entry.getKey())) {
                                            int size = -1;
                                            try {
                                                size = Integer.valueOf(entry.getValue().toString());
                                                if (size == -1) {
                                                    throw new Exception("重新赋值 textSize");
                                                }
                                            } catch (Exception e) {
                                                Log.d(TAG,e.getMessage());
                                                size = (int) (position.getFloatValue("height") * 0.6);
                                            }
                                            params.put("textSize", size);
                                            map.put("textSize", size);
                                        } else if ("textColor".equals(entry.getKey())) {
                                            try {
                                                Color.parseColor(entry.getValue().toString());
                                                params.put("textColor", entry.getValue().toString());
                                            } catch (Exception e) {
                                                Log.d(TAG,e.getMessage());
                                            }
                                        } else if ("duration".equals(entry.getKey())) {
                                            long duration = -1;
                                            try {
                                                duration = Long.valueOf(entry.getValue().toString());
                                                if (duration == -1) {
                                                    throw new Exception("重新赋值 duration");
                                                }
                                            } catch (Exception e) {
                                                Log.d(TAG,e.getMessage());
                                                duration = (long) (map.get("text").toString().length() * 2);
                                            }
                                            params.put("duration", duration);
                                            map.put("duration", duration);
                                        } else if ("backgroundColor".equals(entry.getKey())) {
                                            try {
                                                Color.parseColor(entry.getValue().toString());
                                                params.put("backgroundColor", entry.getValue().toString());
                                            } catch (Exception e) {
                                                Log.d(TAG,e.getMessage());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Toast.makeText(context, "离线目录下存在非法文件名，请删除后重试", Toast.LENGTH_SHORT).show();
                    }

                    return layout.toJSONString();
                }

                @Override
                public void success(String s) {

                    if (null == advPercentView){
                        return;
                    }
                    if (!advPercentView.isInit) {
                        advPercentView.init(config.getViewModel());
                    } else {
                        if (isPause && !isRunning) {
                            return;
                        }
//                        KLog.d(isRunning + " " + isPause);
                        String md5 = FileUtil.getStringMD5(s);
                        Log.d(TAG,"MD5: " + md5 + " " + advPercentView.getLayoutMd5());
                        if (!TextUtils.isEmpty(md5) && !md5.equals(advPercentView.getLayoutMd5())) {
                            advPercentView.parseLayout(s, AdvPercentView.Model.OFF_LINE);
                        }
                    }

                }
            });
        }

    }

    private boolean isImage(File f) {
        return f.getName().endsWith(".png") || f.getName().endsWith(".jpg") || f.getName().endsWith(".JPG") || f.getName().endsWith(".PNG");
    }

    private boolean isVideo(File f) {
        return f.getName().endsWith(".mp4");
    }

    public static class Config {
//        private String host;
        private String licenseCode;
        private long duration;
        private AdvPercentView.Model viewModel;
        private String offLineLayoutName;
        private String localLayout;
        private String localDir = Constant.path_off_line;

        public String getLocalLayout() {
            return localLayout;
        }

        public void setLocalLayout(String localLayout) {
            this.localLayout = localLayout;
        }

        public String getLocalDir() {
            return localDir;
        }

        public void setLocalDir(String localDir) {
            this.localDir = localDir;
        }

        public String getOffLineLayoutName() {
            return offLineLayoutName;
        }

        public void setOffLineLayoutName(String offLineLayoutName) {
            this.offLineLayoutName = offLineLayoutName;
        }

        //        private String appId;
//        private String appSecret;

        public AdvPercentView.Model getViewModel() {
            return viewModel;
        }

        public void setViewModel(AdvPercentView.Model viewModel) {
            this.viewModel = viewModel;
        }

//        public String getHost() {
//            return host;
//        }
//
//        public void setHost(String host) {
//            this.host = host;
//        }


        public long getDuration() {
            return duration;
        }

        public void setDuration(long duration) {
            this.duration = duration;
        }

        public String getLicenseCode() {
            return licenseCode;
        }

        public void setLicenseCode(String licenseCode) {
            this.licenseCode = licenseCode;
        }

        @Override
        public String toString() {
            return "Config{" +
//                    "host='" + host + '\'' +
                    ", licenseCode='" + licenseCode + '\'' +
                    ", duration=" + duration +
                    ", viewModel=" + viewModel +
                    ", offLineLayoutName='" + offLineLayoutName + '\'' +
                    '}';
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEbPreDownload(EbPreDownload eb) {
        preDownload();
    }

    /**
     * 预下载
     */
    private void preDownload() {
        LogUtils.d(TAG,"VideoDownloadManager.isInited = " + VideoDownloadManager.getInstance().isInited());
        if (!VideoDownloadManager.getInstance().isInited()) {
            return;
        }
        long startTime = System.currentTimeMillis();
        final long endTime = startTime + 7 * 24 * 3600 * 1000;
        NetWork.getInstance().get().url(API.newInstance().getDevicePlansVideoList).addParam(Constant.deviceId, SPManager.getLong(Constant.deviceId))
                .addParam("startTime", DateTimeUtil.formatDateTime(startTime, DateTimeUtil.data_format_str_3))
                .addParam("endTime", DateTimeUtil.formatDateTime(endTime, DateTimeUtil.data_format_str_3))
                .build().execute(new NetWorkStringCallBack() {
            @Override
            public void onError(String msg) {
                if (handler != null) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            preDownload();
                        }
                    }, 5000);
                }
            }

            @Override
            public void onResponse(String json) {
                AJsonParser parser = AJsonParser.parser(json);
                if (parser.isOk()) {
                    SPManager.put(Constant.preDownloadTime, endTime);
                    JSONArray array = parser.parseContentArray();
                    if (null == array) {
                        return;
                    }
                    for (int i = 0; i < array.size(); i++) {
                        String url = array.getJSONObject(i).getString("url");
                        url = API.newInstance().doRepleaseResourcePath(url);
                        String md5 = array.getJSONObject(i).getString("md5");
                        if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(url)) {
                            VideoDownloadManager.getInstance().addDownload(url, md5);
                        }
                    }
                } else {
                    if(handler!=null){
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                preDownload();
                            }
                        }, 5000);
                    }

                }
            }
        });
    }

}
